import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/model/image_base.dart';

class SearchPixiv extends StatefulWidget {
  final String tag;
  final bool change;

  const SearchPixiv({super.key, required this.tag, required this.change});
  @override
  State<SearchPixiv> createState() => _SearchImageState();
}

class _SearchImageState extends State<SearchPixiv>
    with AutomaticKeepAliveClientMixin {
  // 文本控制器
  final List<ImageBase> pixivs = [];
  Set<String> results = <String>{};
  bool isLoading = false;
  late SharedPreferences prefs;

  Future<void> getR18() async {
    prefs = await SharedPreferences.getInstance();
    if (widget.tag.isNotEmpty) getData();
  }

  Future<void> getData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    try {
      final r18 = prefs.getInt('r18') ?? 0;
      Response? res1;
      Response? res2;
      try {
        res1 = await getPixiv(tag: widget.tag, r18: r18);
      } catch (e) {
        print('getPixiv error: $e');
      }
      try {
        res2 = await getPixiv2(tag: widget.tag, r18: r18);
      } catch (e) {
        print('getPixiv2 error: $e');
      }

      if (res1 != null) {
        List pics1 = res1.data['data'];
        for (var i = 0; i < pics1.length; i++) {
          ImageBase image = ImageBase(
            largePath: pics1[i]['urls']['original'],
            smallPath: pics1[i]['urls']['medium'],
            tags: (pics1[i]['tags'] as List<dynamic>?)?.join(' ') ?? '',
            width: pics1[i]['size']['width'],
            height: pics1[i]['size']['height'],
          );
          if (!results.contains(image.largePath)) {
            pixivs.add(image);
            results.add(image.largePath);
          }
        }
      }
      if (res2 != null) {
        List pics2 = res2.data['data'];
        for (var i = 0; i < pics2.length; i++) {
          ImageBase image = ImageBase(
            largePath: pics2[i]['urls']['original'],
            smallPath: pics2[i]['urls']['small'],
            tags: (pics2[i]['tags'] as List<dynamic>?)?.join(' ') ?? '',
            width: pics2[i]['width'] ?? 1,
            height: pics2[i]['height'] ?? 1.7,
          );
          if (!results.contains(image.largePath)) {
            pixivs.add(image);
            results.add(image.largePath);
          }
        }
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  // 监听 change 变化
  @override
  void didUpdateWidget(covariant SearchPixiv oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.change != widget.change) {
      setState(() {
        pixivs.clear();
        results = <String>{};
      });
      getData();
    }
  }

  @override
  void initState() {
    super.initState();
    getR18();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ImageList(
        imageList: pixivs,
        isLoading: isLoading,
        isWaterfallFlow: true,
        onImageBottomLoading: () {
          if (isLoading) return;
          getData();
        },
        onImageListRefresh: () {
          setState(() {
            pixivs.clear();
            results = <String>{};
          });
          getData();
        });
  }

  @override
  bool get wantKeepAlive => true;
}
